import VueRouter from "vue-router";
import Vue from "vue";
import routes from "@/router/routes";
import store from "@/store";
Vue.use(VueRouter);
const originPush = VueRouter.prototype.push;
VueRouter.prototype.push =function push(location){
    return originPush.call(this,location).catch(err=>err);
};
const originReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace =function push(location){
    return originReplace.call(this,location).catch(err=>err);
}
const router =  new VueRouter({
    routes,
    // 控制滚动行为,让页面跳转滚动到顶部
    scrollBehavior (to, from, savedPosition) {
        return { y: 0 } // y为0代表滚动到顶部
    }
})
// 路由守卫
router.beforeEach(async (to,from,next)=>{
    const token = store.state.user.token;
    if (token){
        const userInfo = store.state.user.userInfo;
        if (userInfo.name){
            next();
        }else{
            try {
                await store.dispatch('user/getUserInfo');
                next();
            }catch (e) {
                await store.dispatch('user/resetToken');
                next('/login');
            }
        }
    }else{
        next();
    }
})
export default router;